"""
-*- coding:utf-8 -*-
@Time:2025/6/11 14:43
@Author: viawang
@Email:  939654454@qq.com
@Wechat:bluesky___9999
@File:commonmethods.py
"""
import os
import subprocess
import time
from pathlib import Path
import requests
from loguru import logger
from playwright.sync_api import sync_playwright, Error as PWError


class CommonMethods:
    def __init__(self, executable_path, profile_id, debugger_port):
        self.executable_path = executable_path
        self.profile_id = profile_id
        self.debugger_port = debugger_port
        self.profile_dir = f"{Path(__file__).parent}/userdata/.profile_{self.profile_id}"
        os.makedirs(self.profile_dir, exist_ok=True)
        self.douyin_url = "https://www.douyin.com/?recommend=1"

    def launch(self):
        """优先复用已开浏览器 & 已开抖音页；没有则新开浏览器和打开抖音页"""
        self.playwright = sync_playwright().start()  # 启动浏览器驱动进程实例
        try:
            self.browser = self.playwright.chromium.connect_over_cdp(f"http://localhost:{self.debugger_port}")
            logger.info(f"✅ 连接到已存在的浏览器（端口 {self.debugger_port}）")
        except Exception:  # 连接失败 → 启动全新浏览器
            logger.info("🔄 未检测到已存在浏览器，正在启动新浏览器...")
            cmd = [
                self.executable_path,
                f"--remote-debugging-port={self.debugger_port}",
                f"--user-data-dir={self.profile_dir}",
                "--start-maximized",
                "--disable-background-networking",
                "--disable-features=CrashRestore",
                "--disable-features=KeepAliveForTest",
                "--disable-background-timer-throttling",
                "--disable-backgrounding-occluded-windows",
                "--disable-renderer-backgrounding",
                "--no-first-run",
                "--no-default-browser-check",
                "--excludeSwitches=enable-automation",
                "--disable-crash-reporter",
            ]

            self.browser_process = subprocess.Popen(
                cmd,
                creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            time.sleep(2)
            self.browser = self.playwright.chromium.connect_over_cdp(f"http://localhost:{self.debugger_port}")
            logger.info(f"✅ 已连接到新开的的浏览器（端口 {self.debugger_port}）")

        self.context = self.browser.contexts[0] if self.browser.contexts else self.browser.new_context()
        for p in self.context.pages:
            if "www.douyin.com/?recommend=1" in p.url:
                self.page = p
                logger.success(f"📄 复用已打开的抖音推荐页：{p.url}")
                return

        self.page = self.context.new_page()
        self.page.goto(self.douyin_url, wait_until="domcontentloaded")
        logger.success("🆕 新建抖音推荐标签页完成...")

